<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    append-to-body
    width="900px"
    top="30px"
    title="合同处理"
  >
    <div v-if="isSend" class="mb-1">
      <el-button @click="handleView">查看合同</el-button>
      <el-button @click="handleCopy(customerUrl)" class="mr-2">
        <i class="fa fa-link"></i>
        复制链接
      </el-button>
      <el-popover placement="top-start" title="客户签约地址" trigger="hover">
        <div>
          <qr-code :value="customerUrl" :size="140"></qr-code>
        </div>
        <el-button slot="reference">
          <i class="fa fa-qrcode"></i>
          扫描二维码
        </el-button>
      </el-popover>
    </div>
    <table class="table table-bordered table-vertical-middle">
      <colgroup>
        <col width="18%" />
        <col width="32%" />
        <col width="18%" />
        <col width="32%" />
      </colgroup>
      <tr>
        <td class="td-label">贷款主体</td>
        <td>{{ related.customer_name }}</td>
        <td class="td-label">{{ isCompany ? '社会统一信用代码' : '身份证号码' }}</td>
        <td>{{ isCompany ? related.register_no : related.lender_idcard }}</td>
      </tr>
      <tr>
        <td class="td-label">地址/通讯地址</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.entrust_entity_address || '' }}</span>
          <el-input
            v-else
            v-model="editData.entrust_entity_address"
            placeholder="请输入客户地址"
          ></el-input>
        </td>
        <td class="td-label">联系电话</td>
        <td>
          {{ related.mobile_no }}
        </td>
      </tr>
      <tr>
        <td class="td-label">银行名称</td>
        <td>{{ related.bank_name }}</td>
        <td class="td-label">授信金额(万元)</td>
        <td>{{ related.apply_funds }}（{{ warrantyAmountCapital }}）</td>
      </tr>
      <tr>
        <td class="td-label">授信合同编号</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.loan_contract_no || '' }}</span>
          <el-input
            v-else
            v-model="editData.loan_contract_no"
            placeholder="授信合同编号"
          ></el-input>
        </td>
        <td class="td-label">授信期限</td>
        <td>{{ startDate }} - {{ endDate }}</td>
      </tr>
      <tr>
        <td class="td-label">贷款用途</td>
        <td colspan="3" :class="tdClass">
          <div v-if="isView">{{ contract.funds_use_dir || '' }}</div>
          <el-input v-else placeholder="贷款用途" v-model="editData.funds_use_dir"></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">还款方式</td>
        <td colspan="3" :class="tdClass">
          <div v-if="isView">{{ contract.repay_method || '' }}</div>
          <el-input
            v-else
            type="textarea"
            placeholder="还款方式"
            :rows="5"
            v-model="editData.repay_method"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">反担保措施</td>
        <td colspan="3" :class="tdClass">
          <span v-if="isView">{{ contract.gua_method_des }}</span>
          <el-input
            v-else
            type="textarea"
            placeholder="反担保措施"
            :rows="5"
            v-model="editData.gua_method_des"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">合同设置</td>
        <td colspan="3" :class="tdClass">
          <span v-if="isView">
            本合同一式{{ contract.num_copes || '-' }}份，双方各执{{ contract.num_copes_per || '-' }}
            份，办理相关法律手续所需文本按需设置。
          </span>
          <div v-else class="d-flex align-items-center px-2">
            本合同一式
            <el-input
              style="width: 5rem"
              v-model="editData.num_copes_lower"
              placeholder="共计"
              v-input-number="{ min: 0, fixed: 0 }"
            ></el-input>
            份，双方各执
            <el-input
              style="width: 5rem"
              v-model="editData.num_copes_per_lower"
              placeholder="各执"
              v-input-number="{ min: 0, fixed: 0 }"
            ></el-input>
            份，办理相关法律手续所需文本按需设置。
          </div>
        </td>
      </tr>
    </table>

    <div class="text-center py-4" v-if="!isView">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        保存
      </el-button>
    </div>
    <el-dialog
      top="30px"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="coloseContract"
      :visible.sync="entrustView"
    >
      <pdf-view :contractId="contractId" :view-mode="true"></pdf-view>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { nzhToMoney, copyText, nzhToNum } from '@vimi/utils-tool'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
export default {
  components: {
    PdfView,
  },
  props: {
    visible: Boolean,
    queryId: String,
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      related: {},
      submitLoading: false,
      editData: {},
      contract: {},
      entrustView: false,
    }
  },
  watch: {
    visible: {
      handler: function () {
        if (this.visible) {
          this.getData().then(() => {
            this.getContract()
          })
        }
      },
      immediate: true,
    },
  },
  computed: {
    isView() {
      return this.viewMode || +(this.contract.sign_status || 0) > 1
    },
    isCompany() {
      return +this.related.customer_type === 1
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    warrantyAmountCapital() {
      return nzhToMoney(this.related.apply_funds * 10000)
    },
    hasContract() {
      return !!this.contract.entrust_contract_id
    },
    isSend() {
      return +this.contract.sign_status > 0
    },
    contractId() {
      return this.contract.doc_id
    },
    customerUrl() {
      return window.location.origin + '/credit-h5/#/'
    },
    startDate() {
      return this.$utils.dateFormat(this.related.load_date, 'yyyy年MM月dd日')
    },
    endDate() {
      return this.$utils.dateFormat(this.related.load_end_date, 'yyyy年MM月dd日')
    },
  },
  created() {},
  methods: {
    handleView() {
      this.entrustView = true
    },
    coloseContract() {
      this.entrustView = false
    },
    handleCopy(value) {
      const success = copyText(value)
      if (success) {
        this.$message.success('已复制到粘贴板')
      } else {
        this.$message.error('已复制到粘贴失败')
      }
    },
    validator() {
      const enumValidator = {
        entrust_entity_address: '请输入客户通讯地址',
        loan_contract_no: '请输入授信合同号',
        funds_use_dir: '请输入贷款用途',
        repay_method: '请输入还款方式',
        gua_method_des: '请输入反担保措施',
        num_copes_per_lower: '请输入合同份数',
        num_copes_lower: '请输入合同份数',
      }

      const keys = Object.keys(enumValidator)
      for (const key of keys) {
        if (!this.editData[key]) {
          this.$message.error(enumValidator[key])
          return false
        }
      }
      return true
    },
    submit() {
      if (!this.queryId) {
        return
      }
      if (!this.validator()) {
        return
      }
      const data = {
        customer_related_id: this.queryId,
        entrust_entity_name: this.related.customer_name,
        entrust_entity_cert_no: this.isCompany
          ? this.related.register_no
          : this.related.lender_idcard,
        entrust_entity_address: this.editData.entrust_entity_address,
        entrust_entity_phone: this.related.mobile_no,
        bank_name: this.related.bank_name,
        reply_funds_capital: this.warrantyAmountCapital,
        reply_funds_yuan: this.related.apply_funds * 10000,
        reply_funds: this.related.apply_funds,
        sign_date: this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日'),
        sign_status: 1,
        is_online_sign: 1,
        load_end_date: this.endDate,
        load_date: this.startDate,
        num_copes_per_lower: this.editData.num_copes_per_lower,
        num_copes_lower: this.editData.num_copes_lower,

        num_copes_per: this.editData.num_copes_per_lower
          ? nzhToNum(this.editData.num_copes_per_lower)
          : '',
        num_copes: this.editData.num_copes_lower ? nzhToNum(this.editData.num_copes_lower) : '',
        loan_contract_no: this.editData.loan_contract_no,
        funds_use_dir: this.editData.funds_use_dir,
        repay_method: this.editData.repay_method,
        gua_method_des: this.editData.gua_method_des,
        gua_rate: this.related.gua_rate,
        gua_org_id: '42b33648-5691-43fa-8b04-16bf9901260f',
      }
      if (this.hasContract) {
        this.putData(data)
      } else {
        this.postData(data)
      }
    },
    async putData(data) {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(
          this.$serviceName,
          'entrust_contract',
          this.contract.entrust_contract_id,
          data
        )
      )
      this.submitLoading = false
      if (res) {
        this.$message.success('保存委托合同成功')
        this.$emit('success', 0)
        this.beforeClose()
      } else {
        this.$message.error('保存委托合同失败')
      }
    },
    async postData(data) {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, 'entrust_contract', data)
      )
      this.submitLoading = false
      if (res) {
        this.getContract()
        this.$message.success('保存委托合同成功')
        this.$emit('success', 1)
        this.beforeClose()
      } else {
        this.$message.error('保存委托合同失败')
      }
    },
    getData() {
      this.related = {}
      if (!this.queryId) {
        return
      }
      this.loading = true
      return this.$api
        .getData(this.$serviceName, 'customer_related_quick', {
          'customer_related_id.eq': this.queryId,
        })
        .then(res => {
          this.related = res?.data?.[0] ?? {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    getContract() {
      this.editData = {}
      if (!this.queryId) {
        return
      }
      this.$api
        .getData(this.$serviceName, 'entrust_contract', { 'customer_related_id.eq': this.queryId })
        .then(res => {
          this.contract = res?.data?.[0] ?? {}
          this.editData = { ...this.contract }
          this.editData.entrust_entity_address =
            this.editData.entrust_entity_address || this.related.address || ''
          this.editData.funds_use_dir =
            this.editData.funds_use_dir || this.related.funds_use_dir || ''
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
</style>
